<template>

    <div class="dashboard-container">
        <div id="container">
            <el-form :inline="true" align="center">
                <el-form-item label="名称"><el-input v-model="name" placeholder="请输入名称"></el-input></el-form-item>
                     <el-form-item label="角色">
                    <el-select v-model="role" placeholder="请选择角色" clearable>
                        <el-option label="管理员" value="管理员"></el-option>
                        <el-option label="超级管理员" value="超级管理员"></el-option>
                    </el-select>
                </el-form-item>                <el-button type="primary" icon="el-icon-search" @click="pageQuery()">查询</el-button>
                <el-button type="primary" icon="el-icon-close" @click="reset()">重置</el-button>
                <el-button type="primary" icon="el-icon-plus el-icon-plus"
                    @click="dialogFormVisible2 = true">新增</el-button>
            </el-form>
        </div>

        <el-table :data="tableData" stripe style="width: 100% " @selection-change="handleSelectionChange">
            <el-table-column prop="id" label="id" align="center"></el-table-column>
            <el-table-column prop="account" label="账号" align="center"></el-table-column>
            <el-table-column prop="name" label="名称" align="center"> </el-table-column>
            <el-table-column prop="age" label="年龄" align="center"> </el-table-column>
            <el-table-column prop="gender" label="性别" align="center"></el-table-column>
            <el-table-column prop="role" align="center" label="角色"> </el-table-column>
            <el-table-column prop="number" align="center" label="电话"></el-table-column>
            <el-table-column prop="password" align="center" label="密码"></el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="selectById(scope.row.id)">编辑</el-button>
                    <el-button type="primary" size="small" @click="del(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination align="center" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="page" :background="background" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

         <el-dialog title="添加管理员" :visible.sync="dialogFormVisible2">
    <el-form :model="admin" :rules="rules" ref="addForm" label-position="right" label-width="120px">
        <!-- 第一行：账号和名称 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="账号：" prop="account" required>
                    <el-input v-model="admin.account" placeholder="请输入4-16位账号"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="名称：" prop="name" required>
                    <el-input v-model="admin.name" placeholder="请输入2-10位名称"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 第二行：年龄和性别 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="年龄：" prop="age" required>
                    <el-input v-model.number="admin.age" placeholder="18-65岁"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="性别：" prop="gender" required>
                    <el-select v-model="admin.gender" placeholder="请选择性别">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 第三行：权限和电话 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="账号权限：" prop="role" required>
                    <el-select v-model="admin.role" placeholder="请选择权限">
                        <el-option label="管理员" value="管理员"></el-option>
                        <el-option label="超级管理员" value="超级管理员"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="电话号码：" prop="number" required>
                    <el-input v-model="admin.number" placeholder="请输入手机号码"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 密码单独一行 -->
        <el-form-item label="密码：" prop="password" required>
            <el-input v-model="admin.password" type="password" show-password placeholder="8-16位，含大小写和数字"></el-input>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
    </div>
</el-dialog>
</div>
</template>

<script>
import { adminpage, getById, selectById, addadmin } from '@/api/AdminManafe'
export default {
    data() {
        var checkAge = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('年龄不能为空'));
            }
        }
        
        // 验证手机号的函数
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入电话号码'));
            }
            const reg = /^1[3-9]\d{9}$/;
            if (!reg.test(value)) {
                callback(new Error('请输入正确的手机号码'));
            } else {
                callback();
            }
        };

        // 验证密码强度的函数
       const validatePassword = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请输入密码'));
    }
    if (value.length < 6 || value.length > 16) {
        callback(new Error('密码长度需在6-16位之间'));
    } else {
        callback();
    }
};
        return {
            id: null,
            account: null,
            name: null,
            age: null,
            gender: null,
            role: null,
            number: null,
            password: '',
            admin: {
                id: undefined,
                account: null,
                name: null,
                age: null,
                gender: null,
                role: null,
                number: null,
                password: "123456"
            },
            dynamicValidateForm: {
                domains: [{
                    value: ''
                }],
                email: ''
            },
            page: 1,
            pageSize: 10,
            tableData: [],
            total: 0,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormVisible2: false,
            formLabelWidth: '120px',
            // 表单验证规则
            rules: {
                account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                age: [
                    { required: true, message: '请输入年龄', trigger: 'blur' },
                    { type: 'number', message: '年龄必须为数字值', trigger: 'blur' },
                    { validator: (rule, value, callback) => {
                        if (value < 18 || value > 65) {
                            callback(new Error('年龄必须在18-65岁之间'));
                        } else {
                            callback();
                        }
                    }, trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                role: [
                    { required: true, message: '请选择账号权限', trigger: 'change' }
                ],
                number: [
                    { required: true, validator: validatePhone, trigger: 'blur' }
                ],
                password: [
                    { required: true, validator: validatePassword, trigger: 'blur' }
                ]
            }
        }
    },

    //服务启动后自动执行分页查询
    created() {
        this.pageQuery();
    },

    methods: {
        //分页查询
        pageQuery() {
            const params = {
                id: this.id,
                account: this.account,
                name: this.name,
                age: this.age,
                gender: this.gender,
                role: this.role,
                number: this.number,
                password: this.password,
                page: this.page,
                pageSize: this.pageSize
            }
            adminpage(params).then(res => {
                this.total = res.data.data.total
                this.tableData = res.data.data.records
            })
        },

        //重置
        reset() {
            // 重置所有搜索条件
            this.id = null;
            this.account = null;
            this.name = null;
            this.age = null;
            this.gender = null;
            this.role = null;
            this.number = null;
            this.password = null;
            
            // 重置分页参数
            this.page = 1;
            this.pageSize = 10;
            
            // 重新查询
            this.pageQuery();
        },


        //添加
         submitAddForm() {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    addadmin(this.admin).then(res => {
                        this.$message.success("恭喜你，添加成功");
                        this.$router.push('/AdminManage/AdminManage');
                        this.dialogFormVisible2 = false;
                        this.pageQuery();
                    }).catch(error => {
                        this.$message.error("添加失败：" + error.message);
                    });
                } else {
                    this.$message.error('请填写正确的表单信息');
                    return false;
                }
            });
        },

        //删除
        del(id) {
        this.$confirm(`此操作将永久删除ID=${id}的数据, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            return getById(id); // Add return here for proper promise chaining
        }).then(res => {
            if (res.data.code === 1) {
            this.$message.error('删除失败!');
            } else {
            this.$message.success('删除成功!');
            this.pageQuery();
            }
        }).catch(err => {
            if (err !== 'cancel') {
            this.$message.error('删除过程中出错: ' + err.message);
            } else {
            this.$message.info('已取消删除');
            }
        });
        },

        //修改
        selectById(id) {
            this.$router.push({
                path: '/AdminManage/update',
                query: { id: id }
            })
        },



        handleSizeChange(val) {
            this.pageSize = val
            this.pageQuery()
        },
        handleCurrentChange(val) {
            this.page = val
            this.pageQuery()
        },
        // 监控多选框事件
        handleSelectionChange(selection) {
            this.selectNum = selection.length;
            this.selection = selection;
        },

        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        removeDomain(item) {
            var index = this.dynamicValidateForm.domains.indexOf(item)
            if (index !== -1) {
                this.dynamicValidateForm.domains.splice(index, 1)
            }
        },
        addDomain() {
            this.dynamicValidateForm.domains.push({
                value: '',
                key: Date.now()
            });
        }
    }
}


</script>

<style scoped>
.size {
    height: 100%;
    width: 35%;
}
</style>